<?php
class Default_Model_Place extends Zend_Db_Table{

	protected $_name = 'tblPlace';
	protected $_primary = 'Id';

	private $PLACE_TABLE = 'tblPlace';

	protected $db;

	public function __construct(){
		//Goi ket noi voi Zend Db
		$this->db = Zend_Registry::get('connectDB');
	}

	protected $_messageError = null;

	// Đếm số địa điểm
	public function countPlace(){
		$select = $this->db->select()
		->from($this->PLACE_TABLE,array('COUNT(Id) AS totalPlace'));
		$result = $this->db->fetchOne($select);
		return $result;
	}
	
	//Select place by id
	public function selectPlaceById($userId, $id){
		$select = $this->db->select()->from($this->PLACE_TABLE)->where('Id = ?',$id)->where('UserId = ?',$userId);
		$result  = $this->db->fetchAll($select);
		return $result;
	}
	
	//Select place by id
	public function viewPlaceById($id){
		$select = $this->db->select()->from($this->PLACE_TABLE)->where('Id = ?',$id);
		$result  = $this->db->fetchAll($select);
		return $result;
	}
	
	//Select place by id
	public function getPlacePhoto($userId, $id){
		$select = $this->db->select()->from($this->PLACE_TABLE,array('Photo'))->where('Id = ?',$id)->where('UserId = ?',$userId);
		$result  = $this->db->fetchAll($select);
		return $result;
	}

	//Select last place
	public function selectLastPlace($userId){
		$select = $this->db->select()->from($this->PLACE_TABLE)->where('UserId = ?',$userId);
		$select->order('AddedTime DESC')->limit(1);
		$result  = $this->db->fetchAll($select);
		return $result;
	}
	
	// Danh sách địa điểm
	public function listPlaceByUserId($userId){
		$select = $this->db->select()->from($this->PLACE_TABLE)->where('UserId = ?',$userId);
		$select->order('AddedTime DESC');
		$result  = $this->db->fetchAll($select);
		return $result;
	}

	// Danh sách địa điểm mới nhất
	public function listNewestPlace(){
		$select = $this->db->select()->from($this->PLACE_TABLE);
		$select->order('AddedTime DESC')->limit(20);
		$result  = $this->db->fetchAll($select);
		return $result;
	}
	
	// Them moi địa điểm
	public function insertPlace($arrParam = null){
		try {
			$this->db->insert($this->PLACE_TABLE,$arrParam);
			return true;
		} catch (Exception $e) {
			$this->_messageError = $e->getMessage();
			return false;
		}
	}
	
	// Chinh sua địa điểm
	public function editPlace($arrParam = null, $placeId){
		try {
			$this->db->update($this->PLACE_TABLE, $arrParam, 'Id = '.$placeId);
			return true;
		} catch (Exception $e) {
			$this->_messageError = $e->getMessage();
			return false;
		}
	}
	
	// Xoa thong tin dia diem
	public function deletePlaceById($placeId){
		try {
			$this->db->delete($this->PLACE_TABLE,'Id = ' . $placeId);
			return true;
		} catch (Exception $e) {
			$this->_messageError = $e->getMessage();
			return false;
		}
	}

	public function getError(){
		return $this->_messageError;
	}
}